package me.zhengjie.modules.base.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Base64;
import javax.imageio.ImageIO;

import com.google.gson.JsonObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.file.util.IdUtils;
import org.springframework.stereotype.Component;

import static me.zhengjie.modules.biz.constant.GlobalConstant.DEFAULT_CARD_BACKGROUND;

/**
 * 将二维码转为code
 */
@Component
@Slf4j
public class ConvertCardUtil {

    public static String codeToImg(String code,String serverCard,String cardUrl) throws UnsupportedEncodingException {

        // 构建 JSON 字符串并设置 code
        String jsonString = "{\"inv\":\"" + code + "\",\"entry\":\"/pages/profile/index\"}";

        // 对 JSON 字符串进行 Base64 编码
        String base64Encoded = Base64.getEncoder().encodeToString(jsonString.getBytes());

        // 构建 URL
        String url = "https://wx-mp.scyunkou.com/share?cont=" + URLEncoder.encode(base64Encoded, "UTF-8");

        // 检查目录是否存在，不存在则创建
        File directory = new File(serverCard);
        if (!directory.exists()) {
            directory.mkdirs();
        }

        // 自定义文件名，确保唯一性
        String fileName = IdUtils.generateRandomId(16) + "." + "png";
        String filePath = serverCard + fileName;

        // 二维码尺寸
        int qrCodeWidth = 180;
        int qrCodeHeight = 210;

        try {
            // 加载背景图片
            BufferedImage background = ImageIO.read(new File(DEFAULT_CARD_BACKGROUND));
            // 生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, qrCodeWidth, qrCodeHeight);
            // 创建二维码图片
            BufferedImage qrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
            // 在背景图片上绘制二维码
            Graphics2D graphics = background.createGraphics();
            int x = background.getWidth() - qrCodeWidth - 10; // 调整二维码在右边距离背景图片右边的距离
            int y = background.getHeight() - qrCodeHeight - 10; // 调整二维码在下边距离背景图片底部的距离
            graphics.drawImage(qrCodeImage, x, y, qrCodeWidth, qrCodeHeight, null);
            graphics.dispose();
            // 保存合成后的图片
            ImageIO.write(background, "png", new File(filePath));
            log.info("二维码生成成功！");

        } catch (IOException | WriterException e) {
            log.error("二维码生成失败", e);
        }
        return cardUrl + fileName;
    }
}